#include <Arduino.h>
#include <ESP8266WiFi.h> 
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include "screen.h"
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>NTP
WiFiUDP ntpUDP;
NTPClient TimeClient(ntpUDP, "ntp1.aliyun.com", 8 * 3600, 60000); //六万毫秒即一分钟刷新一次
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>API
const char *WeatherAPI = "https://api.seniverse.com/v3/weather/daily.json?key=";
String Temperature = "";
String Humidity = "";
String Weather = "";
String CityName = "cityname";
String WeatherAPIKey = "your_api_key";
static bool InitWeather = false;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void InfoConfig(String _CityName,String _WeatherAPIKey) {
    CityName = _CityName;
    WeatherAPIKey = _WeatherAPIKey;
}

void FetchWeather() {
  if(InitWeather == false) {
    if (WiFi.status() != WL_CONNECTED)
    {
      WiFiClient client;
      HTTPClient http;
      if(http.begin(client,WeatherAPI+WeatherAPIKey+"&location="+CityName+"&language=zh-Hans&unit=c&start=0&day=1")) {
        auto httpCode = http.GET();
        if(httpCode == HTTP_CODE_OK) {
          String payload = http.getString();
          Serial.println(payload);
          DynamicJsonDocument doc(1024);
          deserializeJson(doc,payload);
          String temperaturehigh = doc["results"][0]["daily"][0]["high"];
          String humidity = doc["results"][0]["daily"][0]["humidity"];
          String weather = doc["results"][0]["daily"][0]["text)dat"];
          Temperature = temperaturehigh;
          Humidity = humidity;
          Weather = weather;
          InitWeather = true;
        } else {
          Serial.println("Error on HTTP request: "+http.errorToString(httpCode));
        }
        http.end();
      } else {
        Serial.println("WiFi not connected");
      }
    }
  }
  if(InitWeather == true) {
    ShowWeather(Temperature);
    Serial.println("Temperature: "+Temperature);
    Serial.println("Humidity: "+Humidity);
    Serial.println("Weather: "+Weather);
  }
}
void FetchTime() {
  TimeClient.update();
  int Hour = TimeClient.getHours();
  int Minute = TimeClient.getMinutes();
  String NowTime = String(Hour) + ":" + String(Minute);
  ShowTime(NowTime);
}